<?php
namespace Addons\Button;

use Addons\Button\Model\ButtonDataModel;
use Addons\Module;
use wechat\WeChat;

class Site extends Module {

    // 菜单列表
    public function lists() {
        $model      = new ButtonDataModel();
        $list       = $model->select();
        $this->list = $list;
        $this->make();
    }

    // 添加和设置微信按钮
    public function set() {
        $model = new ButtonDataModel();
        $id    = I('get.id', 0, 'intval');
        if (IS_POST) {
            $data = I('post.', '', '');
            #$data['status'] = 0;
            if ($id > 0) {
                $data['id'] = $id;
            }
            $this->store($model, $data, function () {
                $this->success('保存成功！', site_url('button.lists'));
                exit;
            });
            exit;
        }


        $field = $id ? $model->find($id) : ['title' => '', 'data' => '{"button":[]}'];
        $this->assign('field', $field);
        $this->make();
    }

    // 推送到微信服务器上
    public function push() {
        $model  = new ButtonDataModel();
        $wechat = new WeChat();

        $id = I('get.id', 0, 'intval');

        $info         = $model->find($id);
        $wxButtonMenu = $info['data'];

        if ($wechat->instance('button')->create($wxButtonMenu)) {
            $model->where(['id' => ['neq', $id]])->save(['status' => 0]);
            $model->where(['id' => $id])->save(['status' => 1]);
            $this->success('推送成功', site_url('button.lists'));
            exit;
        }
    }




}
?>